package com.hoangkien.util;

import hirondelle.date4j.DateTime;

import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Switch;

public class Utils {
	public static void setListViewHeightBasedOnChildrenforList(Context ctx,
			ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}

		int totalHeight = listView.getPaddingTop()
				+ listView.getPaddingBottom();
		// int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(),
		// MeasureSpec.AT_MOST);
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			if (listItem instanceof ViewGroup) {
				listItem.setLayoutParams(new LayoutParams(
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
			}
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
//		int height = (totalHeight + (listView.getDividerHeight() * (listAdapter
//				.getCount() - 1)));
		// params.height =
		// (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, height,
		// ctx.getResources().getDisplayMetrics());
		params.height = (totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)));
		listView.setLayoutParams(params);
		listView.requestLayout();
	}


	public static String validateValue(String value) {
		if (value != null && !value.equals("") && !value.equals("null")) {
			return value;
		}
		return "";

	}

	public static int validateIntValue(int intValue) {
		if (intValue != 0) {
			return intValue;
		}
		return 0;

	}

	public static boolean isExternalStorageReadOnly() {
		String extStorageState = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
			return true;
		}
		return false;
	}

	public static boolean isExternalStorageAvailable() {
		String extStorageState = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
			return true;
		}
		return false;
	}

	public static String getTempFileDir(String pathFile) {

		File externalStore = Environment.getExternalStorageDirectory();

		if (externalStore != null) {
			String dir = externalStore.getAbsolutePath()
					+ pathFile;
			File file = new File(dir);
			if (!file.exists()) {
				file.mkdirs();
			}
			return dir;
		}

		return null;
	}



	public static String convertTime(String time){
		String timeconvert = time;
		DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
		DateFormat dateformats = new SimpleDateFormat("yyyy-MM-dd");
		DateFormat dateconvert = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		DateFormat timeFormat = new SimpleDateFormat("HH:mm");

		Calendar cal = Calendar.getInstance();
		Date currentDate = cal.getTime();
		Date	mDate = null ;
		if (time != null){
			try {
				mDate = dateconvert.parse(time);
				Date d= dateformats.parse(time);

				currentDate = dateformats.parse(dateformats.format(currentDate));

				if (mDate != null && currentDate.equals(d)){
					timeconvert = timeFormat.format(mDate);
					return timeconvert;
				}else{
					timeconvert = dateFormat.format(mDate);
					return timeconvert;
				}

			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return timeconvert;
	}

	public static String convertTimePromotion(String time){
		String CvTime ="";
		DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
		DateFormat dateconvert = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date;

		try {
			date = dateconvert.parse(time);
			CvTime = dateFormat.format(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return CvTime;
	}
	public static String convertDateReport(String date){
		String cvDate ="";
		DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy",Locale.getDefault());
		DateFormat dateconvert = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.getDefault());
		Date mdate;

		try {
			mdate = dateFormat.parse(date);
			cvDate = dateconvert.format(mdate);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return cvDate;
	}
	public static String convertDateEndReport(String date){
		String cvDate ="";
		DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy",Locale.getDefault());
		DateFormat dateconvert = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.getDefault());
		Date mdate;
		String result = null ;
		try {
			mdate = dateFormat.parse(date);
			cvDate = dateconvert.format(mdate);
			String []Date=cvDate.split(" ");
			result = Date[0]+" "+"23:59:59";
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	public static String convertTimeSurgery(String time){
		String cvDate ="";
		DateFormat dateFormat = new SimpleDateFormat("HH:mm - dd/MM/yyyy",Locale.getDefault());
		DateFormat dateconvert = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.getDefault());
		Date mdate;

		try {
			mdate = dateconvert.parse(time);
			cvDate = dateFormat.format(mdate);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return cvDate;
	}
	public static String convertDateTimetoString(DateTime dateTime) {
		// Get year, javaMonth, date
		String date = "";
		DateFormat dateconvert = new SimpleDateFormat("yyyy-MM-dd",Locale.getDefault());

		int year = dateTime.getYear();
		int datetimeMonth = dateTime.getMonth();
		int day = dateTime.getDay();

		Calendar calendar = Calendar.getInstance();
		calendar.clear();
		calendar.set(year, datetimeMonth - 1, day);
		date = dateconvert.format(calendar.getTime());

		return date;
	}
	public static DateTime convertDateToDateTime(Date date) {
		// Get year, javaMonth, date
		Calendar calendar = Calendar.getInstance();
		calendar.clear();
		calendar.setTime(date);

		int year = calendar.get(Calendar.YEAR);
		int javaMonth = calendar.get(Calendar.MONTH);
		int day = calendar.get(Calendar.DATE);

		// javaMonth start at 0. Need to plus 1 to get datetimeMonth
		return new DateTime(year, javaMonth + 1, day, 0, 0, 0, 0);
	}


	public static Date convertDateTimeToDate(DateTime dateTime) {
		int year = dateTime.getYear();
		int datetimeMonth = dateTime.getMonth();
		int day = dateTime.getDay();

		Calendar calendar = Calendar.getInstance();
		calendar.clear();

		// datetimeMonth start at 1. Need to minus 1 to get javaMonth
		calendar.set(year, datetimeMonth - 1, day);

		return calendar.getTime();
	}

	public static ArrayList<DateTime> getFullWeeks(int month, int year,
			int startDayOfWeek) {
		ArrayList<DateTime> datetimeList = new ArrayList<DateTime>();

		DateTime firstDateOfMonth = new DateTime(year, month, 1, 0, 0, 0, 0);
		DateTime lastDateOfMonth = firstDateOfMonth.plusDays(firstDateOfMonth.getNumDaysInMonth() - 1);

		// Add dates of first week from previous month
		int weekdayOfFirstDate = firstDateOfMonth.getWeekDay();

		// If weekdayOfFirstDate smaller than startDayOfWeek
		// For e.g: weekdayFirstDate is Monday, startDayOfWeek is Tuesday
		// increase the weekday of FirstDate because it's in the future
		if (weekdayOfFirstDate < startDayOfWeek) {
			weekdayOfFirstDate += 7;
		}

		while (weekdayOfFirstDate > 0) {
			DateTime dateTime = firstDateOfMonth.minusDays(weekdayOfFirstDate
					- startDayOfWeek);
			if (!dateTime.lt(firstDateOfMonth)) {
				break;
			}

			datetimeList.add(null);
			weekdayOfFirstDate--;
		}
		// Add dates of current month
		for (int i = 0; i < lastDateOfMonth.getDay(); i++) {
			datetimeList.add(firstDateOfMonth.plusDays(i));
		}

		// Add dates of last week from next month
		int endDayOfWeek = startDayOfWeek - 1;

		if (endDayOfWeek == 0) {
			endDayOfWeek = 7;
		}


		int endofweek =0;
		if (lastDateOfMonth.getWeekDay() != endDayOfWeek) {
			int i = 1;
			while (true) {
				DateTime nextDay = lastDateOfMonth.plusDays(i);
				datetimeList.add(null);
				i++;
				endofweek ++;
				if (nextDay.getWeekDay() == endDayOfWeek) {
					break;
				}
			}
		}

		int size = datetimeList.size();
		int row = size / 7;
		int numOfDays = (6 - row) * 7;
		int startofnextmonth = 1;
		DateTime lastDateTime = lastDateOfMonth;
		if (numOfDays >0 )
			if (endofweek>0){
				for (int i = 1; i <= numOfDays; i++) {
					DateTime nextDateTime = lastDateTime.plusDays(endofweek);
					endofweek++;
					if (nextDateTime.getWeekDay() < lastDateTime.getWeekDay()){
						datetimeList.add(null);

					}else{
						DateTime nextDateTimetoAdd = lastDateTime.plusDays(startofnextmonth);
						startofnextmonth++;
						datetimeList.add(nextDateTimetoAdd);
					}

				}
			}else{
				for (int i = 1; i <= numOfDays; i++) {
					datetimeList.add(null);
				}
			}

		return datetimeList;

	}

	public static ArrayList<DateTime> getFullWeekend(DateTime time,
			int startDayOfWeek) {
		ArrayList<DateTime> datetimeList = new ArrayList<DateTime>();

		int dayofweek = time.getWeekDay();
		if (dayofweek<startDayOfWeek){
			dayofweek +=7;
		}
		while (dayofweek > 0) {
			DateTime dateTime = time.minusDays(dayofweek
					- startDayOfWeek);
			if (!dateTime.lt(time)) {
				break;
			}

			datetimeList.add(dateTime);
			dayofweek--;
		}
		if (datetimeList.size()<7){
			int otherdate = 7-datetimeList.size();
			for (int i=0;i<otherdate ;i++){
				datetimeList.add(time.plusDays(i));
			}
		}

		return datetimeList;

	}


}
